<template>
  <div class="index-page">
    <headerBox :left-data="leftData" :active="1" />

    <!-- <hearder title="运营与支付BI" /> -->
    <div class="main">
      <div class="center-box blue-border bg">
        <div>
          <div class="title">利润曲线（日曲线）</div>
          <mixChart id="monthDataChart" ref="monthDataChart" :height="'90%'" />
        </div>
        <div>
          <div class="title flex">
            <span>利润叠加（月度完成度）</span>
            <el-button icon="el-icon-arrow-right" circle size="small" />
          </div>
          <tableBox :data="profitData" :show-serial-number="true" height="23vh" />
        </div>
      </div>
      <div class="top-box">
        <div class="green-border flex-box bg">
          <div class="title flex">
            <span>计划收入</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(1)" />
          </div>
          <tableBox :data="plannedIncomeData" />
        </div>
        <div class="green-border flex-box bg">
          <div class="title flex">
            <span>计划成本一-工资</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(2)" />
          </div>
          <tableBox :data="planCost1" :show-serial-number="true" />
        </div>
        <div class="green-border flex-box bg">
          <div class="title flex">
            <span>计划成本二-资产+低值</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(3)" />
          </div>
          <tableBox :data="planCost2" :show-serial-number="true" />
        </div>
        <div class="green-border flex-box bg">
          <div class="title flex">
            <span>计划成本三-税费+抵扣进项</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(4)" />
          </div>
          <tableBox :data="planCost3" :show-serial-number="true" />
        </div>
        <div class="green-border flex-box bg">
          <div class="title flex">
            <span>计划成本四-招待</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(5)" />
          </div>
          <tableBox :data="planCost4" :show-serial-number="true" />
        </div>
      </div>

      <div class="bottom-box">
        <div class="blue-border bg">
          <div class="title flex">
            <span>现金与储蓄状态</span>
            <el-button icon="el-icon-arrow-right" circle size="small" @click="toPlannedIncome(7)" />
          </div>
          <tableBox :data="cashData" :show-serial-number="true" height="24vh" />
        </div>
        <div class="green-border bg">
          <div class="title flex">
            <span>本期应收+历史应收</span>
            <el-button icon="el-icon-arrow-right" circle size="small" />
          </div>
          <tableBox :data="receivableData" :show-serial-number="true" height="24vh" />
        </div>
        <div class="green-border cope-with-box bg">
          <div>
            <div class="title">本期应付-工资</div>
            <div>
              <div><span>总金额</span><span>70236</span></div>
              <div><span>已付款</span><span>70236</span></div>
              <div><span>待付款</span><span>70236</span></div>
            </div>
            <tableBox :data="wagesPayable" :show-thead="true" :thead-list="theadList" height="18vh" />
          </div>
          <div>
            <div class="title">
              <span>本期应付-其他</span>
              <el-button icon="el-icon-arrow-right" circle size="small" />
            </div>
            <div>
              <div><span>总金额</span><span>70236</span></div>
              <div><span>已付款</span><span>70236</span></div>
              <div><span>待付款</span><span>70236</span></div>
            </div>
            <tableBox :data="wagesPayable" :show-thead="true" :thead-list="theadList" height="18vh" />
          </div>
        </div>-
        <div class="orange-border bg">
          <div class="title" @click="toPlannedIncome">
            资金-<span style="color: #ff0000">缺口状态</span>
          </div>
          <tableBox :data="breachData" :show-thead="true" :thead-list="theadList" height="24vh" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import headerBox from '../components/header.vue'
import tableBox from '../components/tableBox.vue'
import mixChart from '../components/mixChart.vue'

import * as echarts from 'echarts'
import {
  getFinanceReportBIContractMoney,
  getFinanceReportBIContractMoneyByRegionRate,
  getFinanceReportBISalarySection,
  getFinanceReportBIMaterialSection,
  getFinanceReportBITaxSection,
  getFinanceReportBIExpenditureSection,
  getFinanceReportBIDataByProfit,
  getFinanceReportBIProfitSection,
  getFinanceReportBIAccountInfoList,
  getFinanceReportBIReceivableAndReceipts
} from '@/api/cld/financeReportBINew'
export default {
  name: 'FinanceReportBI',
  components: {
    headerBox,
    tableBox,
    mixChart
  },
  data() {
    return {
      leftData: {
        title: '成本支付',
        desc: 'Costs and Payments'
      },
      dateVal: '',
      chart: null,
      contractMoney: '',
      planCost1: [], // 计划成本-工资
      planCost2: [], // 计划成本-物资
      planCost3: [], // 计划成本-工资
      planCost4: [], // 计划成本-工资

      chartData: {},
      profitData: [],
      cashData: [],
      receivableData: [],
      plannedIncomeData: [
      ],
      theadList: ['付款金额', '到期天数', '差额'],
      breachData: [
        [
          { val: '10010' },
          { val: '2024-04-12' },
          { val: 11230, style: 'color:#009851' }
        ],
        [
          { val: '47695' },
          { val: '2024-04-12' },
          { val: 11230, style: 'color:#009851' }
        ],
        [
          { val: '66995' },
          { val: '2024-04-12' },
          { val: 11230, style: 'color:#009851' }
        ],
        [
          { val: '47695' },
          { val: '2024-04-12' },
          { val: 11230, style: 'color:#009851' }
        ],
        [
          { val: '47695' },
          { val: '2024-04-12' },
          { val: -11230, style: 'color:#FF0000' }
        ]
      ],
      wagestheadList: ['付款金额', '付款时间', '付款状态'],
      wagesPayable: [
        [{ val: '10010' }, { val: '2024-04-12' }, { val: '未付款' }],
        [{ val: '10010' }, { val: '2024-04-12' }, { val: '未付款' }],
        [{ val: '66995' }, { val: '2024-04-12' }, { val: '未付款' }]
      ]
    }
  },
  computed: {

  },
  mounted() {
    var date = new Date()
    var year = date.getFullYear().toString() // 获取当前年份
    var month = (date.getMonth() + 1).toString()
    if (month < 10) {
      month = '0' + month // 如果月份是个位数，在前面补0
    }
    this.dateVal = year + month
    this.getContractAmount()
    this.getWage()
    this.getSupplies()
    this.getCommission()
    this.getRecessiveness()
    this.getDailyProfit()
    this.getSavingsStatus()
    this.monthlyProfit()
    this.getReceivable()
  },
  methods: {

    abilitySort(arr, property) {
      const map = {}
      for (let i = 0; i < arr.length; i++) {
        const ai = arr[i]
        if (!map[ai[property]]) map[ai[property]] = [ai]
        else map[ai[property]].push(ai)
      }
      const res = []
      Object.keys(map).forEach((key) => {
        res.push({ [property]: key, data: map[key] })
      })
      return res
    },
    // 获取合同总金额
    async getContractAmount() {
      const { data: res } = await getFinanceReportBIContractMoney()

      const data = this.abilitySort(res, 'city')
      let plannedIncomeData = []
      data.forEach(item => {
        let total = 0
        const len = item.data.length
        const cityData = []
        item.data.forEach((info, index) => {
          total = total + info.contractMoney
          if (index == 0 && len - 1 === index) {
            cityData.push([{ val: info.city }, { val: info.business }, { val: this.formatPrice(total) }])
          } else if (index == 0) {
            cityData.push([{ val: info.city, rowspan: len }, { val: info.business }])
          } else {
            cityData.push([{ val: info.business }])
          }

          if (len - 1 === index && index !== 0) {
            cityData[0].push({ val: this.formatPrice(total), rowspan: len })
          }
        })
        plannedIncomeData = [...plannedIncomeData, ...cityData]
      })
      this.plannedIncomeData = plannedIncomeData
    },
    // 获取饼图数据
    async getPieChartData() {
      const { data: res } = await getFinanceReportBIContractMoneyByRegionRate()
      const data = []
      res.forEach((item, index) => {
        data.push({ value: item.contractMoneyRate.toFixed(2), name: item.paramsName })
      })
      this.initplanIncomeChart(data)
    },
    // 获取工资
    async getWage() {
      const { data: res } = await getFinanceReportBISalarySection()
      this.planCost1 = [
        [{ val: '基本工资' }, { val: this.formatPrice(res.basicSalary) }],
        [{ val: '领班津贴' }, { val: this.formatPrice(res.foremanAllowance) }],
        [{ val: '主管津贴' }, { val: this.formatPrice(res.managerAllowance) }],
        [{ val: '经理津贴' }, { val: this.formatPrice(res.handleAllowance) }],
        [{ val: '加班费' }, { val: this.formatPrice(res.verTimeCost || 0) }],
        [
          { val: '基线与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.rvDiff), style: 'color:#FF7830' }
        ],
        [
          { val: '计划与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.pvDiff), style: 'color:#FF7830' }
        ]
      ]
    },
    // 获取物资
    async getSupplies() {
      const { data: res } = await getFinanceReportBIMaterialSection({ dateVal: this.dateVal })
      this.planCost2 = [
        [{ val: '月计划采购额' },
        { val: this.formatPrice(res.suggestionProcureNumber) }],
        [
          { val: '设备折旧/增值' },
          { val: this.formatPrice(res.assetsDepreciation) }
        ],
        [{ val: '月维修费' }, { val: this.formatPrice(res.maintenancePrice) }],
        [{ val: '低值消耗叠加' }, { val: this.formatPrice(res.lowValue) }],
        [{ val: '物资总成本' }, { val: this.formatPrice(res.materialSumCost) }],
        [
          { val: '基线与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.rvDiff), style: 'color:#FF7830' }
        ],
        [
          { val: '计划与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.pvDiff), style: 'color:#FF7830' }
        ]
      ]
    },
    // 获取税费
    async getCommission() {
      const { data: res } = await getFinanceReportBITaxSection()
      this.planCost3 = [
        [{ val: '开票金额' }, { val: 0 }],
        [{ val: '开票税率' }, { val: 0 }],
        [{ val: '税费' }, { val: this.formatPrice(res.taxAmount || 0) }],
        [{ val: '抵扣税费' }, { val: 0 }],
        [{ val: '抵扣后税率' }, { val: 0 }],
        [
          { val: '基线与实际差异', style: 'color:#FF7830' },
          { val: 0, style: 'color:#FF7830' }
        ],
        [
          { val: '计划与实际差异', style: 'color:#FF7830' },
          { val: 0, style: 'color:#FF7830' }
        ]
      ]
    },
    // 隐性支出板块
    async getRecessiveness() {
      const { data: res } = await getFinanceReportBIExpenditureSection()
      this.planCost4 = [
        [{ val: '隐性支出' }, { val: 0 }],
        [{ val: '招待' }, { val: this.formatPrice(res.entertainCost) }],
        [{ val: '福利' }, { val: this.formatPrice(res.benefitCost) }],
        [{ val: '工服' }, { val: this.formatPrice(res.clothesCost) }],
        [{ val: '保险' }, { val: this.formatPrice(res.insuranceCost) }],
        [
          { val: '基线与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.rvDiff), style: 'color:#FF7830' }
        ],
        [
          { val: '计划与实际差异', style: 'color:#FF7830' },
          { val: this.formatPrice(res.pvDiff), style: 'color:#FF7830' }
        ]
      ]
    },
    // 日利润
    async getDailyProfit() {
      const { data: res } = await getFinanceReportBIDataByProfit()
      const chartData = {
        xAxis: [],
        dataRV: [],
        dataPV: [],
        dataAV: []
      }
      res.forEach((item) => {
        chartData.xAxis.push(item.dataName)
        chartData.dataRV.push(item.rv || 0)
        chartData.dataPV.push(item.pv || 0)
        chartData.dataAV.push(item.av || 0)
      })
      this.$refs.monthDataChart.initChart(chartData)
    },
    // 月利润
    async monthlyProfit() {
      const { data: res } = await getFinanceReportBIProfitSection({ dateVal: this.dateVal })

      this.profitData = [
        [{ val: '叠加合同收入' }, { val: 0 }],
        [{ val: '叠加本期应收' }, { val: 0 }],
        [{ val: '叠加总成本' }, { val: 0 }],
        [{ val: '计划利润' }, { val: 0 }],
        [{ val: '实际利润' }, { val: 0 }],
        [{ val: '理论基线差异' }, { val: 0 }],
        [{ val: '理论计划差异' }, { val: 0 }]
      ]
    },
    // 现金与储蓄状态
    async getSavingsStatus() {
      const { data: res } = await getFinanceReportBIAccountInfoList()
      res.forEach((item, index) => {
        if ((index + 1) == res.length) {
          this.cashData.push([{ val: item.paramsName, colspan: 2 }, { val: this.formatPrice(item.amount) }])
        } else {
          this.cashData.push([{ val: item.companyName }, { val: item.paramsName }, { val: this.formatPrice(item.amount) }])
        }
      })
    },
    // 获取应收
    async getReceivable() {
      const { data: res } = await getFinanceReportBIReceivableAndReceipts()
      this.receivableData = [
        [{ val: '本期应收' }, { val: this.formatPrice(res.currentReceivable || 0) }],
        [{ val: '本期实收' }, { val: '暂无' }],
        [{ val: '历史应收' }, { val: this.formatPrice(res.historyReceivable || 0) }],
        [{ val: '历史实收' }, { val: '暂无' }],
        [{ val: '坏账烂账' }, { val: this.formatPrice(res.badDebtAmount || 0) }],
        [
          { val: '本期剩余应收', style: 'color:#FF7830' },
          { val: this.formatPrice(res.currentReceivableDiff || 0), style: 'color:#FF7830' }
        ],
        [
          { val: '历史应收剩余', style: 'color:#FF7830' },
          { val: this.formatPrice(res.historyReceiptDiff || 0), style: 'color:#FF7830' }
        ],
        [
          { val: '总应收', style: 'color:#FF7830' },
          { val: this.formatPrice(res.sumReceivable || 0), style: 'color:#FF7830' }
        ]
      ]
    },
    // 初始化饼图
    initplanIncomeChart(pieData) {
      this.chart = echarts.init(document.getElementById('planIncomeChart'))
      this.chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        title: [
          {
            // 第一个圆环标题
            text: '合计总金额', // 主标题
            textStyle: {
              // 主标题样式
              color: '#666',
              // fontWeight: "",
              fontSize: 14
            },
            left: '48%', // 定位到适合的位置
            top: '40%', // 定位到适合的位置
            subtext: this.contractMoney, // 副标题
            subtextStyle: {
              // 副标题样式
              color: '#333',
              fontSize: 20
            },
            textAlign: 'center' // 主、副标题水平居中显示
          }
        ],
        series: [
          {
            type: 'pie',
            radius: ['50%', '90%'],

            label: {
              normal: {
                formatter: '{b}\n{c}%'
              }
            },
            tooltip: {
              valueFormatter: function (value) {
                return value + '%'
              }
            },
            data: pieData
          }
        ]
      })
    },

    toPlannedIncome(active) {
      this.$router.push({ path: '/report/financeReportBIItme', query: { active } })
    },
    // 千分位格式化并保留两位小数
    formatPrice(price) {
      return price.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  }
}
</script>
<style lang="scss" scoped>
// @import './components/border.css';

.index-page {
  width: 100vw;
  min-height: 100vh;
  background: #F2F4FC;
  position: relative;

  .bg {
    background: rgba(255, 255, 255, 0.6);
    border-radius: 6px;
  }

  .main {
    padding: 14px 16px;
    height: 94vh;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    >div {
      flex-grow: 1;
      flex-shrink: 0;
      margin: 12px 0;
      height: 30vh;
    }

    .title {
      font-weight: bold;
      font-size: 16px;
      color: #333333;
      line-height: 19px;
      text-align: left;
      height: 3vh;
      line-height: 3vh;
      margin: 0;
    }

    .flex {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }


    .top-box {
      display: flex;
      margin: 0 12px;
      justify-content: space-between;

      >div {
        width: 19%;
        flex-shrink: 1;

        margin-bottom: 24px;
        padding: 16px;
        box-shadow: 0px 2px 6px 0px rgba(255, 255, 255, 0.25);
      }

      #planIncomeChart {
        max-width: 18vw;
        max-height: 30vh;
      }

      .flex-box {
        display: flex;
        flex-direction: column;
        padding-bottom: 12px;
      }
    }

    .center-box {
      box-sizing: border-box;
      padding: 16px;
      margin: 0 12px;
      margin-bottom: 24px;
      display: flex;


      >div:nth-child(1) {
        width: 81%;
        border-right: 1px solid #dddddd;
      }

      >div:nth-child(2) {
        flex-grow: 1;
        padding-left: 35px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
      }

      .title {
        font-weight: bold;
        font-size: 16px;
        color: #000000;
        text-align: center;
      }
    }

    .bottom-box {
      box-sizing: border-box;
      margin: 0 12px;
      display: flex;
      justify-content: space-between;

      >div {
        padding: 16px;
        width: 19%;
        display: flex;
        flex-direction: column;
      }

      >div:nth-child(3) {
        width: 39%;
        flex-direction: row;
      }

      .cope-with-box {
        display: flex;
        height: 100%;
        box-sizing: border-box;
        justify-content: space-between;

        >div {
          width: 50%;
          display: flex;
          flex-direction: column;

          .title {
            text-align: center;
            padding-right: 20px;
            position: relative;

            .el-button {
              position: absolute;
              right: 20px;
            }

            span {
              flex-grow: 1;
            }
          }

          >div:nth-child(2) {
            display: flex;
            padding: 0 10px;
            margin-bottom: 16px;

            div {
              display: flex;
              flex-direction: column;
              background: rgba(255, 255, 255, 0.6);
              margin: 0 10px;
              flex-grow: 1;
              text-align: center;
              padding: 10px;
              border-radius: 8px 8px 8px 8px;
              color: #333333;
              font-size: 16px;

              span:nth-child(1) {
                color: #666666;
                font-size: 14px;
                line-height: 28px;
              }
            }
          }

          div:nth-child(3) {
            padding: 0 20px;
            flex-grow: 1;
          }
        }

        >div:nth-child(1) {
          border-right: 1px solid #ddd;
        }
      }
    }
  }
}
</style>
